package com.healthcare.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.healthcare.client.form.ApplyReferralForm;
import com.healthcare.client.mapper.AdminofficeMapper;
import com.healthcare.client.mapper.PatientMapper;
import com.healthcare.client.mapper.TransferttypeMapper;
import com.healthcare.client.pojo.*;
import com.healthcare.client.mapper.ReferralMapper;
import com.healthcare.client.service.ReferralService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.healthcare.client.utils.DateTimeUtils;
import com.healthcare.client.utils.SessionUtils;
import com.healthcare.client.vo.AdminConsultationlListVo;
import com.healthcare.client.vo.DoctorConsultationlListVo;
import com.healthcare.client.vo.DoctorMonadVo;
import com.healthcare.common.constants.ResultCodeEnum;
import com.healthcare.common.exception.KetaiException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 转诊申请 服务实现类
 * </p>
 *
 * @author 新华医院转诊联盟
 * @since 2020-04-13
 */
@Service
public class ReferralServiceImpl extends ServiceImpl<ReferralMapper, Referral> implements ReferralService {

    @Autowired
    private AdminofficeMapper adminofficeMapper;

    @Autowired
    private TransferttypeMapper transferttypeMapper;

    @Autowired
    private PatientMapper patientMapper;

    /**
     * 获取转诊申请页面需要的数据
     * @return
     */
    @Override
    public Map<String, Object> getReferralApplyInfo() {
        // 保存所有信息的map
        Map<String, Object> map = new HashMap<>();
        // 获取session中的值
        Object object =  SessionUtils.getSessionAttr("doctor");
        User user = null;
        // 判断session值是否为空,如果为空则抛出异常
        if(object == null){
            throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
        }
        // 赋值
        user = (User) object;

        // 查询所有转诊科室信息
        QueryWrapper<Adminoffice> adminofficeQueryWrapper = new QueryWrapper<>();
        adminofficeQueryWrapper.eq("is_transfertreatment",0);
        List<Adminoffice> adminofficeList = adminofficeMapper.selectList(adminofficeQueryWrapper);

        // 查询所有门诊类型信息
        QueryWrapper<Transferttype> transferttypeQueryWrapper = new QueryWrapper<>();
        List<Transferttype> transferttypeList =transferttypeMapper.selectList(transferttypeQueryWrapper);

        map.put("adminofficeList",adminofficeList);
        map.put("transferttypeList",transferttypeList);
        map.put("user",user);
        return map;
    }

    /**
     * 添加转诊信息
     * @param applyReferralForm 申请转诊等数据
     * @return
     */
    @Override
    @Transactional
    public Map<String,Object> addReferralInfo(ApplyReferralForm applyReferralForm) {
        // 返回到患者详情的数据
        Map<String,Object> map = new HashMap<>();
        Patient patient = new Patient();
        Referral referral = new Referral();
        BeanUtils.copyProperties(applyReferralForm,referral);
        BeanUtils.copyProperties(applyReferralForm,patient);
        // 判断转诊数据是否为空
        if(StringUtils.isEmpty(referral)){
            throw  new KetaiException(25555,"转诊信息为空");
        }
        // 判断患者数据是否为空
        if(StringUtils.isEmpty(patient)){
            throw  new KetaiException(25556,"患者信息为空");
        }
        // 获取session的值
        Object object =  SessionUtils.getSessionAttr("doctor");
        // 判断session值是否为空,如果为空则抛出异常
        if(object == null){
            throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
        }
        // 添加状态
        referral.setState(0);
        User user = (User) object;
        // 添加操作人
        referral.setOperator(user.getUsername());

        if(!StringUtils.isEmpty(referral.getId())&&!StringUtils.isEmpty(patient.getPatientId())){
            // 修改患者信息和转诊信息
            patientMapper.updateById(patient);
            baseMapper.updateById(referral);
        }
        if(StringUtils.isEmpty(referral.getId())&&StringUtils.isEmpty(patient.getPatientId())){
            // 添加患者信息
            patientMapper.insert(patient);
            // 添加患者id
            referral.setSuffererDetailsId(patient.getPatientId());
            baseMapper.insert(referral);
        }
        map.put("referral",referral);
        map.put("patient",patient);
        return map;
    }

    /**
     * 分页转诊列表数据
     * @param identity 区分身份 0 操作- 1 医生
     * @param page 当前页
     * @param size 分页显示数
     * @return
     */
    @Override
    public PageInfo<AdminConsultationlListVo> getReferralListVo(Integer page, Integer size, Integer identity,Integer sortType,String patientname) {
        // 保存返回数据的list vo
        List<AdminConsultationlListVo> listVoList = null;
        // 通过pagehelper 进行拦截 分页
        PageHelper.startPage(page,size);
        // 当身份为医生时
        if(identity == 1){
            // 获取session的值
            Object object =  SessionUtils.getSessionAttr("doctor");
            // 判断session值是否为空,如果为空则抛出异常
            if(object == null){
                throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
            }
            User user = (User) object;
            // 如果医生有值
            if(!StringUtils.isEmpty(user)){
                listVoList =  baseMapper.getReferralListVo(user.getId(),sortType,patientname);
            }
        }
        // 当身份为操作员时
        if(identity == 0){
            listVoList = baseMapper.getReferralListVo(0,sortType,patientname);
        }
        PageInfo<AdminConsultationlListVo> pageInfo = new PageInfo<AdminConsultationlListVo>(listVoList);
        return pageInfo;
    }

    /**
     *  根据转诊单id,得到转诊单得所有信息
     * @param referralId 转诊单id
     * @return
     */
    @Override
    public List<DoctorMonadVo> getDoctorMonadVoList(Integer referralId) {
        return baseMapper.getDoctorMonadVoList(referralId);
    }

    /**
     * 取消转诊预约，移除转诊信息和患者信息
     * @param id  转诊id
     */
    @Override
    @Transactional
    public void deleteReferralInfo(Integer id) {
       // 查询该转诊信息绑定的患者id
       Referral referral = baseMapper.selectById(id);
       // 删除 患者信息
       patientMapper.deleteById(referral.getSuffererDetailsId());
       // 删除转诊信息
       baseMapper.deleteById(referral.getId());
    }

    /**
     *  返回小助手审核操作需要的数据
     * @param id 转诊id
     * @return
     */
    @Override
    public Map<String, Object> getReferralAuditInformation(Integer id) {
        // 保存所有信息的map
        Map<String, Object> map = new HashMap<>();

        // 查询所有转诊科室信息
        QueryWrapper<Adminoffice> adminofficeQueryWrapper = new QueryWrapper<>();
        adminofficeQueryWrapper.eq("is_transfertreatment",0);
        List<Adminoffice> adminofficeList = adminofficeMapper.selectList(adminofficeQueryWrapper);

        // 查询所有门诊类型信息
        QueryWrapper<Transferttype> transferttypeQueryWrapper = new QueryWrapper<>();
        List<Transferttype> transferttypeList =transferttypeMapper.selectList(transferttypeQueryWrapper);

        Referral referral = baseMapper.selectById(id);

        Patient patient  = patientMapper.selectById(referral.getSuffererDetailsId());

        map.put("adminofficeList",adminofficeList);
        map.put("transferttypeList",transferttypeList);
        map.put("referral",referral);
        map.put("patientName",patient.getPatientname());
        return map;
    }


    /**
     *  小助手审核操作
     * @param referral 转诊对象
     * @param type 0 - 1 用来区分是通过还是拒绝
     */
    @Override
    public void referralAuditInformation(Referral referral, Integer type){
        Object object = SessionUtils.getSessionAttr("admin");
        // 判断session值是否为空,如果为空则抛出异常
        if(object == null){
            throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
        }
        User user = (User) object;
        // 为 0 时通过
        if(type == 0){
            referral.setState(1);
            referral.setOperator(user.getUsername());
        }
        // 为 1 时拒绝
        if(type == 1){
            referral.setState(2);
            referral.setOperator(user.getUsername());
            referral.setRefusedTime(DateTimeUtils.getDateInfo());
        }
        System.out.println(referral);
        baseMapper.updateById(referral);
    }

    /**
     *  查询重新提交后转诊申请需要的数据
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getReferralAuditInformationInfo(Integer id) {
        // 保存所有信息的map
        Map<String, Object> map = new HashMap<>();
        Referral referral = baseMapper.selectById(id);

        Patient patient =  patientMapper.selectById(referral.getSuffererDetailsId());
        map.put("referral",referral);
        map.put("patient",patient);
        return map;
    }

    /**
     *  完成转诊
     * @param referralId     转诊id
     */
    @Override
    public void accomplishReferral(Integer referralId,Integer type) {
        Object object = SessionUtils.getSessionAttr("admin");
        // 判断session值是否为空,如果为空则抛出异常
        if(object == null){
            throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
        }
        User user = (User) object;
        Referral referral = baseMapper.selectById(referralId);
        // 如果type == 0 为完成转诊
        if(type == 0){
            referral.setState(3);
            referral.setSuccessfulTime(DateTimeUtils.getDateInfo());
            referral.setOperator(user.getUsername());
        }
        // 如果type == 1 为撤销转诊
        if(type == 1){
            referral.setState(0);
            referral.setGroupRemark("");
            referral.setGroupDoctor("");
            referral.setOperator(user.getUsername());
            baseMapper.updateById(referral);
        }
        baseMapper.updateById(referral);
    }
}
